﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Infrastructure.DDD
{
    public class RepositoryBase<T> : IRepository<T> where T : Entity
    {
        protected DbContext _dbContext;

        public RepositoryBase(DbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            return _dbContext.SaveChangesAsync(cancellationToken);
        }

        public void Add(T entity)
        {
            _dbContext.Set<T>().Add(entity);
        }

        //public Task AddAsync(T entity)
        //{
        //    return _dbContext.Set<T>().AddAsync(entity);
        //}
        public void AddRange(List<T> entity)
        {
            _dbContext.Set<T>().AddRange(entity);
        }

        public Task AddRangeAsync(List<T> entity)
        {
            return _dbContext.Set<T>().AddRangeAsync(entity);
        }

        public T FindById(int id)
        {
            return _dbContext.Set<T>().Find(id);
        }

        public async Task<T> FindByIdAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }

        public async Task<T> FindByIdWithIncludeAsync<TProperty>(int id, Expression<Func<T, TProperty>> navigationProperty)
        {
            return await _dbContext.Set<T>().Include(navigationProperty).FirstOrDefaultAsync(application => application.Id == id);
        }
        public void Remove(T entity)
        {
            _dbContext.Set<T>().Remove(entity);
        }

        public void RemoveRange(List<T> entity)
        {
            _dbContext.Set<T>().RemoveRange(entity);
        }

        public void Update(T entity)
        {
            _dbContext.Set<T>().Update(entity);
        }

        public void UpdateRange(List<T> entity)
        {
            _dbContext.Set<T>().UpdateRange(entity);
        }

        public IQueryable<T> AsQueryable()
        {
            return _dbContext.Set<T>();
        }
    }
}
